<?php

namespace app\admin\service;

use app\admin\model\Exam;
use think\facade\Db;

/**
 * 考试管理-服务类
 * @author 小码哥
 * @since 2020/11/15
 * Class ExamService
 * @package app\admin\service
 */
class ExamService extends BaseService
{
    /**
     * 构造函数
     * @author 小码哥
     * @since 2020/11/15
     * ExamService constructor.
     */
    public function __construct()
    {
        $this->model = new Exam();
    }

    /**
     * @return array
     * @throws \think\db\exception\DbException
     * 获取列表
     */
    public function getList()
    {
        $sort = 'id desc';
        // 常规查询条件
        $param = request()->param();
        $map = [];
        if ($param) {
            // 筛选标题
            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            if (isset($param['title']) && $param['title']) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $count = $this->model
            ->where($map)
            ->count();
        $ids = $this->model
            ->where($map)
            ->order($sort)
            ->page(PAGE, PERPAGE)
            ->column("id");
        $map[] = ['id', 'in', $ids];
        $field = '';
        $list = $this->model->getAllInfo($map, $field);
        if (empty($list)) {
            //获取数据总数
            //返回结果
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
                "count" => $count,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        }
        foreach ($list as &$item) {
            $array = explode(',', $item['topic_ids']);
            $item['topic_ids'] = array_map('intval', $array);
        }
        //获取数据总数
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        unset($list, $count, $map, $param, $ids);
        return $message;
    }

    /**
     * 添加或编辑
     * @return array
     * @since 2020/11/21
     * @author 小码哥
     */
    public function edit()
    {
        // 请求参数
        $data = request()->param();
        $isExam = $this->checkIsEdit($data['id']);
        if ($isExam == false) {
            return message('已有人参与考试,不支持修改', false);
        }
        $allscore = $this->sumExamScore($data['topic_ids']);
        $data['all_score'] = $allscore;
        $topic_ids = $data['topic_ids'];
        $topic_name = Db::name('topic_data')
            ->whereIn('id', $topic_ids)
            ->column('title');
        $data['topic_ids'] = implode(',', $topic_ids);
        $data['topic_name'] = implode('、', $topic_name);
        // 头像处理
        return parent::edit($data); // TODO: Change the autogenerated stub
    }

    /**
     * 考试期间禁止修改信息
     */
    private function checkIsEdit($exam_id)
    {
        $where = [
            ['mark', '=', 1],
        ];
        $log = Db::name('exam_log')
            ->where($where)
            ->where('exam_id', $exam_id)
            ->column('id');
        if (empty($log)) {
            return true;
        }
        return false;
    }

    /**
     * 设置状态
     * @return array
     * @since 2023/11/14
     * @author 小码哥
     */
    public function status()
    {
        $data = request()->param();
        // 记录ID
        $id = getter($data, "id", 0);
        if (!$id) {
            return message('记录ID不能为空', false);
        }
        // 状态
        $status = getter($data, "status", 0);
        if (!$status) {
            return message('记录状态不能为空', false);
        }
        $error = '';
        $item = [
            'id' => $id,
            'status' => $status
        ];
        if ($status == 1) {
            Db::name('exam')
                ->where('mark', 1)
                ->update(['status' => 2]);
        }
        $rowId = $this->model->edit($item, $error);
        if (!$rowId) {
            return message($error, false);
        }
        return message();
    }

    /**
     * 计算总分数
     */
    public function sumExamScore($topic_ids)
    {
        $allscore = Db::name('topic_data')
            ->whereIn('id', $topic_ids)
            ->sum('all_score');
        return $allscore;

    }

    /**
     * 获取考试下拉列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 小码哥
     * @since 2023/11/14
     */
    public function getExamSelectList()
    {
        $where = [
            ['mark', '=', 1],
        ];
        $list = $this->model->where($where)
            ->field('id,title')
            ->select()
            ->toArray();
        return message("操作成功", true, $list);
    }

}